package cs275.ants.graphics;

import java.util.Random;

import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.TriMesh;

import cs275.ants.agent.Ant;
import cs275.ants.agent.AntMazeIntegrationTest;
import cs275.ants.graph.Maze;
import cs275.ants.graph.base.Graph;
import cs275.ants.graph.base.GraphVertex;

public class Character {
	private TriMesh model;
	private int STEP=3;//1000
	public static final int MAXSTEP=3;
	private Vector3f destination;
	private Vector3f source;
	public boolean isUpdate=false;
	private Ant antBrain;
	private Graphics graphics;
	public void setUp(Maze maze,Graphics graphics){
		Graph graph=maze.getGraph();
		antBrain=new Ant(graph, graph.getVertex(0, 0));
		this.graphics=graphics;
	}
	public TriMesh getModel() {
		return model;
	}

	public void setModel(TriMesh model) {
		this.model = model;
	}
	
	public void setDestination(Vector3f destination){
		this.destination=destination;
		Vector3f noise=graphics.getCellScreenCoordinate(1, 1);
		noise.x*=Math.random()>=0.5?Math.random()/4:-Math.random()/4;
		noise.z*=Math.random()>=0.5?Math.random()/4:-Math.random()/4;
		this.destination.x+=noise.x;
		this.destination.z+=noise.z;
		source=model.getLocalTranslation();
		isUpdate=true;
	}
	
	public void update(){
		if(isUpdate){
			model.lookAt(destination, new Vector3f(0.0f, 1.0f, 0.0f));
			correctAntDirection();
			if (STEP > 0) {
				model.getLocalTranslation().interpolate(source, destination, 1.0f / STEP--);
			} else {
				resetState();
			}
		}else{
			GraphVertex nextDestination=antBrain.chooseNextMove();
			setDestination(graphics.getCellScreenCoordinate(nextDestination.getRow(), nextDestination.getCol()));
			antBrain.move(nextDestination);
		}
	}

	private void correctAntDirection() {
		Quaternion q = new Quaternion(new float[] { 0, -FastMath.HALF_PI, 0 });
		// Ant normally turn to wrong direction this will correct it
		model.setLocalRotation(model.getLocalRotation().mult(q));
	}
	private void resetState(){
		isUpdate=false;
		STEP=MAXSTEP;
		destination=null;
	}
}
